import json
import logging

from flask import Blueprint, request

from app.Controllers.BaseController import BaseController
from app.Models.DoorVehicles import DoorVehicles
from app.Models.Model import DoorVehicle
from app.Models.SapMaterialDetailsInfos import SapMaterialDetailsInfos
from app.Models.VehicleParts import VehicleParts
from app.Vendor.Utils import Utils

doorVehicle = Blueprint('vehicle', __name__)

log = logging.getLogger('error_msg')


@doorVehicle.route('/getVehicle', methods=['POST'])
def get_vehicle():
    vin = request.json.get('vin')
    vehicles = DoorVehicles()
    vehicle_info = vehicles.get_one_by_vin(vin)
    if not vehicle_info:
        vehicle_info = DoorVehicle()
    return Utils.format_date(vehicle_info.to_dict())


@doorVehicle.route('/getNextVehicle', methods=['POST'])
def get_next_vehicle():
    vin = request.json.get('vin')
    vehicles = DoorVehicles()
    vehicle_info = vehicles.get_one_by_vin(vin)
    if not vehicle_info:
        next_vehicle = DoorVehicle()
    else:
        next_vehicle = vehicles.get_next_vehicle(vehicle_info)
    return Utils.format_date(next_vehicle.to_dict())


@doorVehicle.route('/getSapPart', methods=['POST'])
def get_sap_part():
    vehicle_part_id = request.json.get('vehicle_part_id')
    sap_material = SapMaterialDetailsInfos()
    part_list = sap_material.get_one_by_vehicle_part_id(vehicle_part_id)
    part_list = [Utils.format_date(c.to_dict()) for c in part_list]
    return BaseController().success(data=part_list)


@doorVehicle.route('/getAll', methods=['POST'])
def get_all():
    vehicles = DoorVehicles()
    vehicles_list = vehicles.get_all()
    for v in vehicles_list:
        Utils.format_date(v)
    return json.dumps(vehicles_list)


@doorVehicle.route('/addVehicle', methods=['POST'])
def add_vehicle():
    vehicles = DoorVehicles()
    vehicles.add(DoorVehicles.from_dict(request.json))
    return BaseController().success(msg='成功')


@doorVehicle.route('/addVehiclePart', methods=['POST'])
def add_vehicle_part():
    vehicle_parts = VehicleParts()
    vehicle_parts.add(VehicleParts.from_dict(request.json))

    return BaseController().success(msg='成功', data=vehicle_parts.add(VehicleParts.from_dict(request.json)))


@doorVehicle.route('/addMaterialPart', methods=['POST'])
def add_material_part():
    sap_parts = SapMaterialDetailsInfos()
    for material_part in json.loads(request.json):
        sap_parts.add(SapMaterialDetailsInfos.from_dict(material_part))
    return BaseController().success(msg='成功')


@doorVehicle.route('/getNumber', methods=['POST'])
def get_number():
    start_vin = request.json.get('start_vin')
    end_vin = request.json.get('end_vin')

    vehicles = DoorVehicles()
    start_vehicle = vehicles.get_one_by_vin(start_vin)
    end_vehicle = vehicles.get_one_by_vin(end_vin)
    num = vehicles.get_number(start_vehicle, end_vehicle)

    return BaseController().success(msg='成功', data=num)
